package dao;

import conexao.FabricaDeConexao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import model.Usuarios;

public class JDBCUsuarioDAO implements ValidaUsuarioDAO{

    private static FabricaDeConexao conecta = new FabricaDeConexao();
    Connection conexao;
    Statement st;
    ResultSet rs;
    String query;

    public JDBCUsuarioDAO(FabricaDeConexao conecta,
            Connection conexao, Statement st, ResultSet rs, String query) {
        JDBCUsuarioDAO.setConecta(conecta);
        this.conexao = conexao;
        this.st = st;
        this.rs = rs;
        this.query = query;
    }

    @Override
    public boolean VerLogin(String login, String senha) {
        Connection con = getConecta().fazConexao();

        String sql = "SELECT * FROM usuarios WHERE email = '" + login + "' AND cpf = '" + senha + "'";

        int sw = 0;
        try {

            PreparedStatement valores = (PreparedStatement) con.prepareStatement(sql);
            ResultSet result = (ResultSet) valores.executeQuery();

            if (result.next()) {
                if (result.getString(1) == null) {
                    sw = 0;
                } else {
                    sw = 1;
                }
            }
            valores.close();
        } catch (SQLException e) {
            System.out.println("Erro na inserçao de dados!" + e.getMessage());
        } finally {
            conecta.fechaConexao();
        }
        if (sw == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void inserirUsuario(Usuarios novoUsuario) {
        String SQL = "insert into usuarios(nome,cpf,data_nascimento,telefone,email)"
                + "values(?,?,?,?,?)";

        try {
            PreparedStatement p = (PreparedStatement) this.conexao
                    .prepareStatement(SQL);
            p.setString(1, novoUsuario.getNome());
            p.setString(2, novoUsuario.getCpf());
            p.setString(3, novoUsuario.getDataNascimento());
            p.setString(4, novoUsuario.getTelefone());
            p.setString(5, novoUsuario.getEmail());

            p.execute();
        } catch (Exception e) {
            System.out.println("NÃO DEU" + e);
        }
    }

    public static FabricaDeConexao getConecta() {
        return conecta;
    }

    public static void setConecta(FabricaDeConexao conecta) {
        JDBCUsuarioDAO.conecta = conecta;
    }
}
